import React,{Component,Fragment} from 'react'
import {Card,Button,Modal,Form,Input,Select,Tree,Transfer} from 'antd'
import ETable from './../../components/ETable'
import Utils from './../../utils/utils'
import axios from './../../axios'
import menuConfig from './../../config/menuConfig'
const FormItem = Form.Item
const Option = Select.Option
const TreeNode = Tree.TreeNode
export default  class Permission extends Component {
    state = {
        roleVisible:false,
        premVisible:false,
        userAuthVisible:false,
        detailInfo:'',
        menuInfo:''
    }
    params = {
        page: 1
    }
    componentWillMount() {
        this.requestList()
    }
    requestList = () => {
        axios.requestList(this,'/role/list',this.params,true)
    }
    //点击创建角色，弹出modal
    handleRole = () => {
        this.setState({
            roleVisible:true
        })
    }
    
    roleSubmit = () => {
        this.setState({
            roleVisible:false
        })
        let data = this.RoleForm.props.form.getFieldsValue()
        axios.requestList(this,'/role/create',data,true)
        //清除表单数据
        this.RoleForm.props.form.resetFields()
        this.requestList()
    }

    handlePermission = () => {
        const item = this.state.selectedItem
        if(!item) {
            Modal.info({
                title:'温馨提示',
                content:'请选择一个角色',
                okText:'关闭'
            })
            return
        }
        this.setState({
            menuConfig,
            detailInfo:item,
            menuInfo:item.menus,
            premVisible:true
        })
    }
    premSubmit = () => {
        let data = this.PremissionForm.props.form.getFieldsValue()
        data.role_id = this.state.selectedItem.id;
        data.menus = this.state.menuInfo;
        axios.ajax({
            url:'/permission/edit',
            data:{
                params:{
                    ...data
                }
            }
        }).then((res)=>{
            if(res){
                this.setState({
                    premVisible:false,
                    detailInfo:'',
                    menuInfo:''
                })
                this.PremissionForm.props.form.resetFields()
                this.requestList();
            }
        })
    }
    //点击用户授权按钮，弹出框
    handleUserAuth = () => {
        const item = this.state.selectedItem
        if(!item) {
            Modal.info({
                title:'温馨提示',
                content:'未选中任何项目',
                okText:'关闭'
            })
            return
        }
        const role_id = item.id
        axios.ajax({
            url:'/role/user_list',
            data:{
                params:{
                    id:role_id
                }
            }
        }).then(res => {
            if(res){
                let data = res.result
                let dataS=[]
                let targetSource = []
                data.map((item,index) => {
                    item.key = item.user_id
                    dataS.push(item)
                    if(item.status === 0) {
                        targetSource.push(item.key)
                    }
                })
                this.setState({
                    detailInfo:item,
                    dataS,
                    targetSource,
                    userAuthVisible:true
                })
            }
        })
        
    }
    //modal ok按钮
    userAuthSubmit = () => {
        //角色名
        let role_id = this.state.detailInfo.id
        //用户名
        let user_id = this.state.targetSource
        axios.ajax({
            url:'/role/user_role_edit',
            data:{
                params:{
                    role_id:role_id,
                    user_id:user_id
                }
            }
        }).then((res)=>{
            if(res){
                this.setState({
                    userAuthVisible:false,
                    detailInfo:'',
                    dataSource:'',
                    targetSource:''
                })
                this.requestList();
            }
        })
    }
    render(){
        const columns = [
            {
                title:'角色ID',
                dataIndex:'id'
            },
            {
                title:'角色名称',
                dataIndex:'role_name'
            },
            {
                title:'创建时间',
                dataIndex:'create_time',
                render:(create_time) => {
                    return Utils.formateDate(create_time)
                }
            },
            {
                title:'使用状态',
                dataIndex:'status',
                render:(status) => {
                    return status===1?'启用':'停用'
                }
            },
            {
                title:'授权时间',
                dataIndex:'authorize_time',
                render:(authorize_time) => {
                    return Utils.formateDate(authorize_time)
                }
            },
            {
                title:'授权人',
                dataIndex:'authorize_user_name'
            }
        ]
        return (
            <Fragment>
                <Card>
                    <Button type="primary" onClick={this.handleRole}>创建角色</Button>
                    <Button type="primary" onClick={this.handlePermission}>设置权限</Button>
                    <Button type="primary" onClick={this.handleUserAuth}>用户授权</Button>
                </Card>
                <div className="content-wrap">
                    <ETable
                        updateSelectedItem={Utils.updateSelectedItem.bind(this)}
                        selectedRowKeys={this.state.selectedRowKeys}
                        columns = {columns}
                        dataSource = {this.state.dataSource}
                        pagination = {this.state.pagination}
                    />
                </div>
                <Modal
                    title="创建角色"
                    width={600}
                    visible={this.state.roleVisible}
                    onCancel={() => {
                        this.RoleForm.props.form.resetFields()
                        this.setState({
                            roleVisible:false
                        })
                    }}
                    onOk={this.roleSubmit}
                >
                    <RoleForm wrappedComponentRef={(comp) => {this.RoleForm = comp}}/>
                </Modal>
                <Modal
                    title="权限设置"
                    width={600}
                    visible={this.state.premVisible}
                    onCancel={() => {
                        this.PremissionForm.props.form.resetFields()
                        this.setState({
                            premVisible:false
                        })
                    }}
                    onOk={this.premSubmit}
                >
                    <PremissionForm  
                        menuInfo = {this.state.menuInfo || []} 
                        detailInfo={this.state.detailInfo}
                        patchMenuInfo = {(data) => {
                            //重新修改menuInfo值
                            this.setState({
                                menuInfo:data
                            })
                        }} 
                        wrappedComponentRef={(comp) => {this.PremissionForm = comp}}/>
                </Modal>
                <Modal
                    title="用户授权"
                    width={1000}
                    visible={this.state.userAuthVisible}
                    onCancel={() => {
                        this.UserAuthForm.props.form.resetFields()
                        this.setState({
                            userAuthVisible:false
                        })
                    }}
                    onOk={this.userAuthSubmit}
                >
                    <UserAuthForm 
                        detailInfo={this.state.detailInfo} 
                        dataS={this.state.dataS} 
                        targetSource={this.state.targetSource}
                        patchUserAuthForm = {(data) => {
                            //重新修改menuInfo值
                            this.setState({
                                targetSource:data
                            })
                        }} 
                        wrappedComponentRef={(comp) => {this.UserAuthForm = comp}}
                    />
                </Modal>
            </Fragment>
        )
    }
}
class RoleForm extends Component {
    render() {
        const {getFieldDecorator} = this.props.form
        const formItemLayout = {
            labelCol:{
                span:5
            },
            wrapperCol:{
                span:10
            }
        }
        return (
            <Form layout="horizontal">
                <FormItem label="角色名称" {...formItemLayout}>
                    {
                        getFieldDecorator('role_name',{
                            initialValue:''
                        })(
                            <Input placeholder="请输入角色名"/>
                        )
                    }
                </FormItem>
                <FormItem label="状态" {...formItemLayout}>
                    {
                        getFieldDecorator('status',{
                            initialValue:1
                        })(
                            <Select>
                                <Option value={1}>启用</Option>
                                <Option value={0}>停用</Option>
                            </Select>
                        )
                    }
                </FormItem>
            </Form>
        )
    }
}

RoleForm = Form.create({})(RoleForm)

class PremissionForm extends Component {
    renderTreeNodes(data,key='') {
        return data.map((item) => {
            let parentKey = key+item.key;
            if(item.children) {
                return (
                    <TreeNode title={item.title} key={parentKey}>
                        {this.renderTreeNodes(item.children,parentKey)}
                    </TreeNode>
                )
            }
            return <TreeNode title={item.title} key={item.key}></TreeNode>
        })
    }

    onCheck=(checkedKeys) => {
        //调用父元素的方法
        this.props.patchMenuInfo(checkedKeys)
    }
    render() {
        const {getFieldDecorator} = this.props.form
        const formItemLayout = {
            labelCol:{
                span:5
            },
            wrapperCol:{
                span:10
            }
        }
        const detailInfo = this.props.detailInfo
        const menuInfo = this.props.menuInfo
        return (
            <Form layout="horizontal">
                <FormItem label="角色名称" {...formItemLayout}>
                    <Input disabled value={detailInfo.role_name}/>
                </FormItem>
                <FormItem label="状态" {...formItemLayout}>
                    {
                        getFieldDecorator('status',{
                            initialValue:detailInfo.status
                        })(
                            <Select>
                                <Option value={1}>启用</Option>
                                <Option value={0}>停用</Option>
                            </Select>
                        )
                    }
                </FormItem>
                <Tree
                    checkable
                    defaultExpandAll
                    onCheck={(checkedKeys)=>this.onCheck(checkedKeys)}
                    checkedKeys={menuInfo ||[]}
                >
                    <TreeNode title="平台权限" key="platform_all">
                        {this.renderTreeNodes(menuConfig)}
                    </TreeNode>
                </Tree>
            </Form>
        )
    }
}

PremissionForm = Form.create({})(PremissionForm)


class UserAuthForm extends Component {
    filterOption = (inputValue, option) => {
        return option.user_name.indexOf(inputValue) > -1;
    }
    handleChange = (targetKeys) => {
        this.props.patchUserAuthForm(targetKeys)
    }
    render() {
        const {getFieldDecorator} = this.props.form
        const formItemLayout = {
            labelCol:{
                span:5
            },
            wrapperCol:{
                span:19
            }
        }
        const detailInfo = this.props.detailInfo
        return (
            <Form layout="horizontal">
                <FormItem label="角色名称" {...formItemLayout}>
                    <Input disabled value={detailInfo.role_name} style={{width:300}}/>
                </FormItem>
                <FormItem label="选择用户" {...formItemLayout}>
                    <Transfer
                        listStyle={{width: 200,height: 400}}
                        titles={['待选用户', '已选用户']}
                        showSearch
                        searchPlaceholder='输入用户名'
                        filterOption={this.filterOption}
                        dataSource={this.props.dataS}
                        targetKeys={this.props.targetSource}
                        onChange={this.handleChange}
                        render = {item => item.user_name}
                    />
                </FormItem>
            </Form>
        )
    }
}

UserAuthForm = Form.create({})(UserAuthForm)